package core.android.qrcode.decode;

import android.graphics.Bitmap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPointCallback;
import com.google.zxing.common.HybridBinarizer;

import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.Map;

import core.android.tools.AK;

/**
 * @author : XQ
 * @since 2.0
 * 二维码图片解码成文本信息
 */
public enum QRDecoder {
    INSTANCE;
    public static final String TAG = QRDecoder.class.getSimpleName();

    private static MultiFormatReader mMultiFormatReader;
    private static Map<DecodeHintType, Object> hints;

    private ResultPointCallback resultPointCB;

    static {
        mMultiFormatReader = new MultiFormatReader();
        hints = new EnumMap<>(DecodeHintType.class);
        Collection<BarcodeFormat> decodeFormats = new ArrayList<>();
        decodeFormats.addAll(DecodeFormatManager.PRODUCT_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.INDUSTRIAL_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.AZTEC_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.PDF417_FORMATS);
        hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        AK.d();
    }

    /**
     * 结果点
     *
     * @param resultPointCallback
     */
    public QRDecoder addResultPoint(ResultPointCallback resultPointCallback) {
        if (resultPointCB == resultPointCallback) {
            return this;
        }
        this.resultPointCB = resultPointCallback;
        if (resultPointCB != null)
            hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCB);
        mMultiFormatReader.setHints(hints);
        return this;
    }

    public Result decode(Bitmap imageBitmap) {
        //获取初始化的设置器
        RGBBitmapLuminanceSource source = new RGBBitmapLuminanceSource(imageBitmap);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result = null;
        try {
            result = mMultiFormatReader.decode(binaryBitmap);
        } catch (Exception e) {

        } finally {
            mMultiFormatReader.reset();
        }
        return result;
    }

    public Result decodeWithState(BinaryBitmap image) throws NotFoundException {
        return mMultiFormatReader.decodeWithState(image);
    }
}
